import 'dart:ui';
import 'package:flame/components.dart';
import 'package:flutter/material.dart';

class Circle extends PositionComponent with HasGameRef {
  final Paint paint = Paint()
    ..style = PaintingStyle.stroke
    ..strokeWidth = 1;

  ///速度
  Vector2 v = Vector2.zero();

  ///加速度
  Vector2 a = Vector2.zero();
  final Color color;
  final String tag;

  Circle({required this.tag, this.color = Colors.white})
      : super(size: Vector2(60, 60), anchor: Anchor.center);

  @override
  void onGameResize(Vector2 size) {
    position = Vector2(gameRef.size.x / 2, gameRef.size.y / 2);
    super.onGameResize(size);
  }

  @override
  Future<void> onLoad() async {
    paint.color = color;
    position = gameRef.size / 2;
    a = Vector2(0, 150);
    v = Vector2(180, 150);
  }

  @override
  void render(Canvas canvas) {
    super.render(canvas);
    canvas.translate(size.x / 2, size.y / 2);
    canvas.drawCircle(Offset.zero, size.x / 2, paint);
  }

  @override
  void update(double dt) {
    super.update(dt);
    v += a * dt;
    position += v * dt;
    Vector2 winSize = gameRef.size;
    if (position.y > winSize.y - size.y / 2) {
      position.y = winSize.y - size.y / 2;
      v.y = -v.y;
    }

    if (position.y < size.y / 2) {
      position.y = size.y / 2;
      v.y = -v.y;
    }

    if (position.x > winSize.x - size.x / 2) {
      position.x = winSize.x - size.x / 2;
      v.x = -v.x;
    }

    if (position.x < size.x / 2) {
      position.x = size.x / 2;
      v.x = -v.x;
    }
  }

  @override
  void onRemove() {
    super.onRemove();
    print(tag);
  }
}
